/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */

package com.px.pa.modulars.circle.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.util.SecurityUtils;
import com.px.pa.constants.*;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.service.*;
import com.px.pa.modulars.circle.vo.DateCountVo;
import com.px.pa.modulars.circle.vo.DynamicVo;
import com.px.pa.modulars.circle.vo.OriginatorVo;
import com.px.pa.modulars.solr.service.SolrService;
import com.px.pa.modulars.upms.entity.SysUser;
import com.px.pa.modulars.upms.service.SysUserService;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/circledynamicqa")
@Api(value = "circledynamicqa", tags = "问答管理")
public class CircleDynamicQasController {

    private final CircleDynamicService circleDynamicService;
    private final CircleUserService circleUserService;
    private final CircleDynamicPraiseService circleDynamicPraiseService;
    private final CircleDynamicIsseeService circleDynamicIsseeService;
    private final CircleDynamicClassService circleDynamicClassService;
    private final CircleDynamicViewsService circleDynamicViewsService;

    private final SolrService solrService;
    @Value("${solr_core.dyCore}")
    private String collection;
    @Autowired
    private SysUserService sysUserService;
    private SysUser getUser(){

        System.out.println(SecurityUtils.getUser());
        SysUser user = sysUserService.getById(SecurityUtils.getUser().getId());
        return user;
    }
    /**
     * 分页查询
     *
     * @param page          分页对象
     * @param circleDynamic
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getCircleDynamicPage(Page page, CircleDynamic circleDynamic) {
        String tenant = getUser().getOnlyLogo();
        Page<CircleDynamic> circleDynamicPage = circleDynamicService.page(page, new QueryWrapper<CircleDynamic>().like(circleDynamic.getTitle() != null, "title", circleDynamic.getTitle())
                .eq("tenant_code",tenant)
                .eq("type", CircleDynamic.TYPE_QA)
                .eq(circleDynamic.getDynamicClass() != null, "dynamic_class", circleDynamic.getDynamicClass())
                .eq(circleDynamic.getDynamicType() != null, "dynamic_type", circleDynamic.getDynamicType())
                .eq(circleDynamic.getUid() != null, "uid", circleDynamic.getUid())
                .between(circleDynamic.getCreateTimeStart() != null, "create_time", circleDynamic.getCreateTimeStart(), circleDynamic.getCreateTimeEnd())
                .ne("learning_type", LearningTypeEnum.LEARNING_TYPE_ENUM_TWO.getValue())
                .orderByDesc("create_time"));
        circleDynamicPage.getRecords().forEach(a -> {
            //计算点赞数
            int praiseNum = circleDynamicPraiseService.count(new QueryWrapper<CircleDynamicPraise>().eq("dynamic", a.getId()));
            a.setPraiseNum(praiseNum);
            if (a.getDynamicClass() != null) {
                CircleDynamicClass circleDynamicClass = circleDynamicClassService.getById(a.getDynamicClass());
                a.setDynamicClassName(circleDynamicClass.getName());
            }
            List<CircleDynamicIssee> circleDynamicIsseeList = circleDynamicIsseeService.list(new QueryWrapper<CircleDynamicIssee>().eq("dynamic", a.getId()));
            List<CircleUser> users = new ArrayList<>();
            List<String> uids = new ArrayList<>();
            circleDynamicIsseeList.forEach(circleDynamicIssee -> {
                CircleUser circleUser = circleUserService.getById(circleDynamicIssee.getUid());
                uids.add(circleUser.getId().toString());

            });
            String str = org.apache.commons.lang3.StringUtils.join(uids, ",");
            a.setIds(str);
            circleDynamic.setCircleUserList(users);

            /**
             * 文章时长化简为秒，
             */
            if (a.getUid().equals(AdminEnum.ADMIN_ENUM.getValue())) {
                if (a.getDynamicType().equals(DynamicTypeEnum.DYNAMIC_TYPE_ENUM_ONE.getValue())) {

                    a.setReadTime(Math.ceil(a.getTime() / 60));
                } else {
                    a.setReadTime(Math.ceil(a.getTime()));
                }
            }
        });
        return R.ok(circleDynamicPage);
    }


    /**
     * 通过id查询
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleDynamic_circledynamic_get')")
    public R getById(@PathVariable("id") Integer id) {
        CircleDynamic circleDynamic = circleDynamicService.getById(id);

        return R.ok(circleDynamic);
    }

    /**
     * 新增
     *
     * @param circleDynamic
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping
    //  @PreAuthorize("@pms.hasPermission('circleDynamic_circledynamic_add')" )
    public R save(@RequestBody CircleDynamic circleDynamic) {
        String tenant = getUser().getOnlyLogo();
        String randomSecret = ToolUtil.getRandomString(32);
        circleDynamic.setCreateTime(LocalDateTime.now());
        circleDynamic.setUid(AdminEnum.ADMIN_ENUM.getValue()); //超级管理员
        circleDynamic.setType(TypeEnum.TYPE_ENUM_ONE.getValue());  //1.知识
        circleDynamic.setUname("管理员");
        circleDynamic.setTenantCode(tenant);
        circleDynamic.setDynamicNumber(randomSecret);
        circleDynamicService.save(circleDynamic);
        //新增必看人
        if (StringUtils.isNotEmpty(circleDynamic.getIds())) {
            CircleDynamic circleDynamic1 = circleDynamicService.getOne(new QueryWrapper<CircleDynamic>().eq("dynamic_number", randomSecret));
            if (circleDynamic1 != null) {
                List<String> l = Arrays.asList(org.apache.commons.lang3.StringUtils.split(circleDynamic.getIds(), ","));
                l.forEach(a -> {
                    //新增必读人员
                    circleDynamicIsseeService.add(circleDynamic1.getId(), Integer.parseInt(a));
                    //必读人员新增浏览记录
                    circleDynamicViewsService.addNow(circleDynamic1, Integer.parseInt(a));

                });
            }
        }

        try {
            solrService.addDynamicSolr(collection, circleDynamic);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }

        return R.ok();
    }

    /**
     * 修改
     *
     * @param circleDynamic
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('circleDynamic_circledynamic_edit')")
    public R updateById(@RequestBody CircleDynamic circleDynamic) {
        circleDynamicService.updateUser(circleDynamic);
        circleDynamicService.updateById(circleDynamic);

        try {
            solrService.addDynamicSolr(collection, circleDynamic);
        } catch (IOException e) {
            e.printStackTrace();
            return R.failed("添加到索引库失败");
        } catch (SolrServerException e) {
            e.printStackTrace();
            return R.failed("添加到索引库失败");
        }
        return R.ok();
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleDynamic_circledynamic_del')")
    public R removeById(@PathVariable Integer id) {
        circleDynamicService.removeById(id);

        try {
            solrService.deleteById(collection, id);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     * 修改文章展示状态
     *
     * @return R
     */
    @ApiOperation(value = "修改文章展示状态", notes = "修改文章展示状态")
    @GetMapping("/edit")
    public R updateById(@RequestParam("id") Integer id) {
        CircleDynamic circleDynamic = circleDynamicService.getById(id);

        if (circleDynamic.getIsShow().equals(IsShowEnum.IS_SHOW_ENUM_ONE.getValue())) {
            circleDynamic.setIsShow(IsShowEnum.IS_SHOW_ENUM_TWO.getValue());
        } else if (circleDynamic.getIsShow().equals(IsShowEnum.IS_SHOW_ENUM_TWO.getValue())) {
            circleDynamic.setIsShow(IsShowEnum.IS_SHOW_ENUM_ONE.getValue());
        }
        circleDynamicService.updateById(circleDynamic);

        try {
            solrService.addDynamicSolr(collection, circleDynamic);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 修改文章展示状态
     *
     * @return R
     */
    @ApiOperation(value = "修改文章展示状态", notes = "修改文章展示状态")
    @GetMapping("/edit/copy")
    public R updateById1(@RequestParam("id") Integer id) {
        CircleDynamic circleDynamic = circleDynamicService.getById(id);

        if (circleDynamic.getIsCopy().equals(IsCopyEnum.IS_COPY_ENUM_ONE.getValue())) {
            circleDynamic.setIsCopy(IsCopyEnum.IS_COPY_ENUM_TWO.getValue());
        } else if (circleDynamic.getIsCopy().equals(IsCopyEnum.IS_COPY_ENUM_TWO.getValue())) {
            circleDynamic.setIsCopy(IsCopyEnum.IS_COPY_ENUM_ONE.getValue());
        }
        circleDynamicService.updateById(circleDynamic);


        try {
            solrService.addDynamicSolr(collection, circleDynamic);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     * 详情
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "详情", notes = "详情")
    @GetMapping("/details/{id}")
    public R getById1(@PathVariable("id") Integer id) {
        return R.ok(circleDynamicService.getById(id));
    }


    /**
     * 首页统计
     *
     * @return R
     */
    @ApiOperation(value = "首页统计", notes = "首页统计")
    @GetMapping("/home/count")
    public R getHomeCount() {
        Map<String, Object> map = new HashMap<>();
        int userNum = circleUserService.count();
        int dynamicNum = circleDynamicService.count();
        map.put("userNum", userNum);
        map.put("dynamicNum", dynamicNum);
        return R.ok(map);
    }

    /**
     * 首页统计图
     *
     * @return R
     */
    @ApiOperation(value = "首页统计图", notes = "首页统计图")
    @GetMapping("/home/count/figure")
    @Inner(value = false)
    public R getCountFigure() {
        List<DateCountVo> dateCountVoList = new ArrayList<>();
        List<String> dateList = getDaysBetwwen(7);
        for (String str : dateList) {
            DateCountVo dateCountVo = new DateCountVo();
            int count = circleUserService.count(new QueryWrapper<CircleUser>().le("create_time", str));
            dateCountVo.setDtae(str);
            dateCountVo.setNum(count);
            dateCountVoList.add(dateCountVo);
        }
        return R.ok(dateCountVoList);

    }

    /**
     * 获取最近几天的数据
     *
     * @param days
     * @return
     */
    private static Date getDateAdd(int days) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH, -days);
        return c.getTime();
    }

    private static List<String> getDaysBetwwen(int days) { //最近几天日期
        List<String> dayss = new ArrayList<>();
        Calendar start = Calendar.getInstance();
        start.setTime(getDateAdd(days));
        Long startTIme = start.getTimeInMillis();
        Calendar end = Calendar.getInstance();
        end.setTime(new Date());
        Long endTime = end.getTimeInMillis();
        Long oneDay = 1000 * 60 * 60 * 24L;
        Long time = startTIme;
        while (time <= endTime) {
            Date d = new Date(time);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println(df.format(d));
            dayss.add(df.format(d));
            time += oneDay;
        }
        return dayss;
    }


    /**
     * 上传文章的人员列表
     *
     * @return R
     */
    @ApiOperation(value = "上传文章的人员列表", notes = "上传文章的人员列表")
    @GetMapping("/get/user/list")
    @Inner(value = false)
    public R getUserList() {

        List<CircleDynamic> circleDynamicList = circleDynamicService.list(new QueryWrapper<CircleDynamic>().groupBy("uid"));
        List<OriginatorVo> originatorVoList = new ArrayList<>();
        circleDynamicList.forEach(circleDynamic -> {
            OriginatorVo originatorVo = new OriginatorVo();
            originatorVo.setId(circleDynamic.getUid());
            if (circleDynamic.getUid() == -1) {
                originatorVo.setName("管理员");
            } else {
                CircleUser circleUser = circleUserService.getById(circleDynamic.getUid());
                originatorVo.setName(circleUser.getName());

            }
            originatorVoList.add(originatorVo);
        });
        return R.ok(originatorVoList);
    }


    /**
     * 后台添加的知识列表添加到学习包
     *
     * @return R
     */
    @ApiOperation(value = "后台添加的知识列表添加到学习包", notes = "后台添加的知识列表添加到学习包")
    @GetMapping("/knowledge/list")
    @Inner(value = false)
    public R getList(@RequestParam("name") String name) {
        List<CircleDynamic> circleDynamicList = circleDynamicService.list(new QueryWrapper<CircleDynamic>().eq("uid", AdminEnum.ADMIN_ENUM.getValue())
                .eq("learning_type", LearningTypeEnum.LEARNING_TYPE_ENUM_ONE.getValue())
                .like(StringUtils.isNotEmpty(name), "title", name));
        List<DynamicVo> dynamicVoList = new ArrayList<>();
        circleDynamicList.forEach(circleDynamic -> {
            DynamicVo dynamicVo = new DynamicVo();
            dynamicVo.setId(circleDynamic.getId());
            if (circleDynamic.getDynamicType().equals(DynamicTypeEnum.DYNAMIC_TYPE_ENUM_ONE.getValue())) {
                dynamicVo.setName(circleDynamic.getTitle() + "/" + DynamicTypeEnum.DYNAMIC_TYPE_ENUM_ONE.getDesc());
            } else if (circleDynamic.getDynamicType().equals(DynamicTypeEnum.DYNAMIC_TYPE_ENUM_TWO.getValue())) {
                dynamicVo.setName(circleDynamic.getTitle() + "/" + DynamicTypeEnum.DYNAMIC_TYPE_ENUM_TWO.getDesc());
            } else if (circleDynamic.getDynamicType().equals(DynamicTypeEnum.DYNAMIC_TYPE_ENUM_THREE.getValue())) {
                dynamicVo.setName(circleDynamic.getTitle() + "/" + DynamicTypeEnum.DYNAMIC_TYPE_ENUM_THREE.getDesc());
            }

            dynamicVoList.add(dynamicVo);
        });

        return R.ok(dynamicVoList);

    }

    /**
     * 详情
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "详情", notes = "详情")
    @GetMapping("/detailsByid/{id}")
    @Inner(value = false)
    public R getDetails(@PathVariable("id") Integer id) {
        CircleDynamic circleDynamic = circleDynamicService.getById(id);
        return R.ok(circleDynamic);
    }


}
